package com.huluobo.a2202kotlindouyindemo.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2202kotlindouyindemo.MainActivity
import com.huluobo.a2202kotlindouyindemo.R
import com.huluobo.a2202kotlindouyindemo.databinding.ActivityLoginBinding
import com.huluobo.base.bean.Money
import com.huluobo.base.db.AppDBUtils
import com.huluobo.base.net.Const
import com.huluobo.base.view.BaseMVVMActivity
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient

class LoginActivity : BaseMVVMActivity<ActivityLoginBinding>() {
    private lateinit var viewModel: LoginViewModel

    override fun initData() {
        viewModel = ViewModelProvider(this)[LoginViewModel::class.java]

        viewModel.loginSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                //登录成功保存用户token
                SPUtils.getInstance().put(Const.PARAM_TOKEN, it.data.token)
                //保存用户到数据库中
                SPUtils.getInstance().put(Const.PARAM_USERNAME, it.data.username)
                AppDBUtils.getDb().getUserInfoDao().insertUserInfo(it.data)
                AppDBUtils.getDb().getMoneyDao().insertUserMoney(Money(0, it.data.username, 10000f))

                EMClient.getInstance().login(it.data.username, it.data.password, object : EMCallBack {
                    override fun onSuccess() {
                        val intent = Intent(this@LoginActivity, MainActivity::class.java)
                        startActivity(intent)
                        finish()
                    }

                    override fun onError(code: Int, error: String?) {
                        Log.i("TagA", "code:$code,msg:$error")
                    }
                })
            }
        }

        viewModel.loginFailed.observe(this) {
            Log.i("TagA", "登录失败:$it")
        }

    }

    override fun initView() {
        dataBinding.loginToLoginBtn.setOnClickListener {
            viewModel.login(
                dataBinding.loginUsername.text.toString(),
                dataBinding.loginPassword.text.toString()
            )
        }
    }

    override fun getLayoutId() = R.layout.activity_login
}